package com.example.testio;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.res.AssetManager;
import android.os.Environment;

public class ListDataManager {

	File card_file;
	String in_file_name;
	String ex_file_name;
	AssetManager am;

	public ListDataManager(File card_file, String file_name, AssetManager am) {
		this.card_file = card_file;
		this.in_file_name = file_name;
		this.ex_file_name = file_name;
		this.am = am;
	}
	
	public boolean hasCard() {
		String state = Environment.getExternalStorageState();
		return Environment.MEDIA_MOUNTED.equals(state);
    }
	
	public boolean hasFile() {
    	File file = new File(card_file, ex_file_name);
        return file.exists();
    }
	
	public void createFile() throws IOException {
        
    	InputStream is = am.open(in_file_name);
        File file = new File(card_file, ex_file_name);
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        
	     try {
	        	
	    	in = new BufferedInputStream(is);
	        out = new BufferedOutputStream(new FileOutputStream(file));
	    	int b;
	        while( (b = in.read()) != -1) {
	          out.write(b);
	        }
	    	  
	      } finally {
	    	  if (in != null) {
	    		  in.close();
	    	 }
	    	  
	    	 if (out != null) {
	    		  out.close();
	    	 }
		  }
    }

	public List<String> readFile() throws IOException {
    	List<String> res = new ArrayList<String>();
    	File file = new File(card_file, ex_file_name);
    	BufferedReader input = null;  
    	try {
    		input = 
					new BufferedReader(
							new InputStreamReader(
									new FileInputStream(file)));
        	  
			String strLine;
			while ((strLine = input.readLine()) != null)   {
				res.add(strLine);
				}
        	  
          } finally {
	    	  if (input != null) {
	    	    input.close();
	    	 }
    	  }
    	
    	return res;
    }
}
